import os
from collections import Counter
import os
import shutil
import glob


def count_first_chars_in_txt(folder_path):
    # 初始化一个Counter对象用于统计字符
    char_counter = Counter()

    # 遍历文件夹
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            # 确保文件是txt文件
            if file.endswith('.txt'):
                file_path = os.path.join(root, file)

                # 读取文件，统计每行第一个字符
                with open(file_path, 'r', encoding='utf-8') as f:
                    for line in f:
                        # 只考虑非空行，并确保第一字符是字母或数字（根据实际需求调整）
                        if line.strip():
                            first_char = line[0]
                            if first_char.isalnum():  # 确保是字母或数字
                                char_counter[first_char] += 1

    # 输出统计结果
    for char, count in char_counter.items():
        print(f"'{char}': {count} times")


def delete_empty_files(folder_a_path,folder_b_path):

    # 文件夹A和B的路径
    # folder_a_path = 'path/to/folderA'
    # folder_b_path = 'path/to/folderB'

    # 遍历文件夹B中的文件
    for filename in os.listdir(folder_b_path):
        b_file_path = os.path.join(folder_b_path, filename)

        # 检查文件大小是否为0
        if os.path.isfile(b_file_path) and os.path.getsize(b_file_path) == 0:
            a_file_path = os.path.join(folder_a_path, filename)

            # 检查文件夹A中是否有同名文件
            if os.path.exists(a_file_path):
                # 删除文件夹A中的文件
                try:
                    os.remove(a_file_path)
                    print(f"Deleted from Folder A: {filename}")
                except Exception as e:
                    print(f"Error deleting from Folder A: {e}")

            # 删除文件夹B中的文件
            try:
                os.remove(b_file_path)
                print(f"Deleted from Folder B: {filename}")
            except Exception as e:
                print(f"Error deleting from Folder B: {filename}")

    print("Deletion process completed.")


def delete_files_with_prefix(directory, prefix):
    """
    删除指定目录及其子目录下所有指定前缀的文件。

    :param directory: 要搜索的目录路径
    :param prefix: 要删除的文件名前缀
    """
    # 构建一个glob模式来匹配所有以指定前缀开始的文件
    pattern = os.path.join(directory, f"**/{prefix}*")

    # 使用glob.glob找到所有匹配的文件
    files_to_delete = glob.glob(pattern, recursive=True)

    # 遍历文件列表并删除每个文件
    for file_path in files_to_delete:
        try:
            os.remove(file_path)
            print(f"Deleted: {file_path}")
        except Exception as e:
            print(f"Error deleting {file_path}: {e}")



if __name__ == '__main__':
    # 使用示例：将下面的'your_folder_path'替换为你的文件夹路径
    folder_path = r"D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\cron\label_force"
    count_first_chars_in_txt(folder_path)
    # delete_files_with_prefix(folder_path, 'corn')

    # folder_a_path = r"C:\Users\64531\Desktop\weed-datasets\allcorn weed datasets\img1"
    # folder_b_path = r"C:\Users\64531\Desktop\weed-datasets\allcorn weed datasets\label"
    # delete_empty_files(folder_a_path,folder_b_path)